/* jslint unused: false */
/* global $, Backbone, _, console, alert, _global, motify */
$(function() {

    'use strict';

    var isAdmin = window._global.is_owner_team;
    var isMobile = window._global.is_mobile;

    // 正则匹配微信版本
    var ua = window.navigator.userAgent;
    var wxCheck = ua.match(/MicroMessenger\/(\d+(\.\d+)*)/);
    var isWx = wxCheck !== null && wxCheck.length;
    var wxVer = (isWx) ? parseFloat(wxCheck[1]) : 0;
    var permissions = {
        wxPay: window._global.wxpay_env,
        aliPay: window._global.alipay_env
    };
    var outBuyUrl = $('.js-buy-it').data('out-buy') || '';
    var supportOutBuy = !! (outBuyUrl.replace('http://', ''));

    var tapName = isMobile ? 'touchstart' : 'click';
    var notWxBuy = !window._global.wxpay_env;

    // 工具类
    var Utils = window.Utils || {};

    // 扩展工具类
    $.extend(Utils, {
        validNumber: function(value) {
            return /^\d+$/.test(value);
        },

        validEmail: function(value) {
            return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
        },

        // 需要用户再次确认
        needConfirm: function(msg, yesClk, noClk) {

            var result = window.confirm(msg);

            if (result) {
                if (yesClk && typeof yesClk === 'function') {
                    yesClk.apply();
                }
            } else {
                if (noClk && typeof noClk === 'function') {
                    noClk.apply();
                }
            }
        }
    });

    // ----------------------- The Model Definitions ---------------------- //
    var Gm = Backbone.Model.extend({

        defaults: {
            // id: '', // sid
            name: '',
            active: false,
            unavailable: false
        },

        initialize: function() {
            var model = this;

            model.set({
                cid: model.collection.idx
            });
        },

        toggleActive: function() {
            var model = this;

            model.set({
                active: !model.get('active')
            });
        },

        toggleUnavailable: function(flag) {
            var model = this;

            model.set({
                unavailable: flag
            });
        }

    });


    // ----------------------- The Collection Definitions ---------------------- //
    var GmList = Backbone.Collection.extend({

        model: Gm,

        findActive: function() {
            return this.findWhere({
                active: true
            });
        },

        clearActive: function() {
            var activeGm = this.findActive();
            if (activeGm) {
                activeGm.toggleActive();
            }
            return activeGm;
        }

    });

    var Stash = Backbone.Collection.extend({

        model: Gm,

        initialize: function(models, options) {
            var that = this;

            that.maxSize = options.maxSize;

            that.listenTo(that, 'add', that.plus);
            that.listenTo(that, 'remove', that.minus);
        },

        // 检查已选择的sku条件个数
        checkSize: function(mode) {
            var that = this;

            var size = that.size();
            var maxSize = that.maxSize;


            if (mode === 'plus') {
                return (size === maxSize - 1);
            } else if (mode === 'minus') {
                if (size < 3) {
                    return (size === maxSize - 1);
                } else {
                    return (size === maxSize - 2);
                }
            } else {
                return false;
            }
        },

        // 添加sku条件选择
        plus: function() {
            var that = this;

            var size = that.size();
            var maxSize = that.maxSize;
            if (size === maxSize) {
                var sku = that.getLast();
                that.trigger('full:stash', sku, that.models);
            } else {
                that.checkStock('plus');
            }
        },

        // 取消sku条件选择
        minus: function() {
            var that = this;

            that.checkStock('minus');
            that.trigger('not_full:stash', null);
        },

        // 查找剩下的sku数据
        getLast: function(models) {
            var that = this;

            models = models || that.models;
            var keys = _(models).pluck('id');
            console.log(keys);

            var last = _({}).extend(window._global.sku.map);
            for (var i = 0, len = keys.length; i < len; i++) {
                last = last[keys[i]];
            }
            return last;
        },

        // 检查库存
        checkStock: function(mode) {
            var that = this;

            var _list = window._global.sku.list;
            if (that.checkSize(mode)) {
                var last = that.getLast();
                console.log('最后的值：', last);

                _.each(last, function(value, key) {
                    var _stock = _list[value].stock_num;
                    var model = window.allGms.get(key);

                    // 仅当model存在时才检查库存
                    if (model) {
                        model.toggleUnavailable(_stock <= 0);
                        console.log(model.get('unavailable'));
                    }
                });
            } else {
                window.allGms.each(function(model) {
                    model.toggleUnavailable(false);
                });
            }
        }


    });


    // ----------------------- The View Definitions ---------------------- //
    var GmView = Backbone.View.extend({

        tagName: 'li',
        className: '',
        template: _.template('<%=name %>'),

        events: function() {
            if (isMobile) {
                return {
                    'touchstart': 'toggleActive'
                };
            } else {
                return {
                    'click': 'toggleActive'
                };
            }
        },

        initialize: function(options) {
            var view = this;

            view.listenTo(view.model, 'change', view.render);
        },

        render: function() {
            var view = this;

            view.$el.html(view.template(view.model.toJSON()));
            view.$el.toggleClass('active', view.model.get('active'));
            view.$el.toggleClass('unavailable', view.model.get('unavailable'));

            return view;
        },

        toggleActive: function() {
            var view = this;

            var model = view.model;

            // 当前元素class名中如果含有 unavailable 则返回
            if (model.get('unavailable')) {
                return;
            }
            var collection = view.model.collection;

            // 当前元素是否激活
            var isActive = model.get('active');
            if (!isActive) {

                // 重置其他已激活的元素的激活状态并返回该元素
                var _active = collection.clearActive();
                if (_active) {

                    // 将其从 stash 中移除
                    window.stash.remove(_active);
                }

                // 添加当前元素到 stash 中
                window.stash.add(model);

                // 切换为激活状态
                model.toggleActive();

            } else {

                // 从stash中移除当前元素
                window.stash.remove(model);

                // 切换为未激活状态
                model.toggleActive();

            }

        }

    });

    var GmListView = Backbone.View.extend({

        // el: '.model-list',

        initialize: function(options) {
            var view = this;

            view.collection = new GmList([]);
            view.collection.parentView = options.parentView;
            view.collection.idx = options.idx;

            view.listenTo(view.collection, 'add', view.addOne);
            view.listenTo(view.collection, 'reset', view.render);

            view.collection.reset(options.collection);
            window.allGms.add(view.collection.models);
        },

        render: function() {
            var view = this;

            view.addAll();
        },

        addOne: function(model) {
            var view = this;

            var item = new GmView({
                model: model
            });
            var itemEle = $(item.render().el);
            view.$el.append(itemEle);
        },

        addAll: function() {
            var view = this;

            view.$el.empty();

            var collection = view.collection;

            collection.each(view.addOne, view);
        }

    });

    // 购买数量
    var QuantityView = Backbone.View.extend({

        // el: '.js-quantity',

        events: function() {
            if (isMobile) {
                return {
                    'touchstart .minus': 'minus',
                    'touchstart .plus': 'plus',
                    'blur .txt': 'checkQuantity'
                };
            } else {
                return {
                    'click .minus': 'minus',
                    'click .plus': 'plus',
                    'blur .txt': 'checkQuantity'
                };
            }
        },

        initialize: function(options) {
            var view = this;

            view.quota = view.max = options.max;
            view.minusEle = view.$('.minus');
            view.plusEle = view.$('.plus');
            view.txtIpt = view.$('.txt');
            view.val = view.txtIpt.val() || 1;

            view.listenTo(view, 'update_max', view.updateMax);
        },

        updateMax: function(stock) {
            var view = this;

            stock = Number(stock);

            // 限购为0的情况，即可以无限制购买
            // if (view.quota === 0) {
            //     return false;
            // }

            // 库存小于原限购数量
            if (stock < view.quota) {

                view.max = stock;

            } else {

                view.max = view.quota;

            }

            // 如果当前购买数大于目前最大购买量
            if (view.val > view.max) {
                view.txtIpt.val(view.max);
                motify.log('购买数量超过库存。');
            }
        },

        getQuantity: function() {
            var view = this;

            var val = view.val = view.txtIpt.val();
            val = parseInt(val, 10);
            return val;
        },

        setQuantity: function(num) {
            var view = this;

            view.val = num;
            view.txtIpt.val(num);
            view.trigger('set_quantity', num);
        },

        minus: function() {
            event.preventDefault();
            var view = this;

            var val = view.getQuantity();
            if (val > 1) {
                view.setQuantity(val - 1);
            } else {
                view.setQuantity(1);
            }
        },

        plus: function(event) {
            event.preventDefault();
            var view = this;

            var val = view.getQuantity();
            if (view.max === 0 || val < view.max) {
                view.setQuantity(val + 1);
            } else {
                view.setQuantity(view.max);
            }
        }

    });

    var AdvOptsView = Backbone.View.extend({

        // el: '.adv-opts',

        template: _.template($('#tmpl-adv-opts').html()),

        initialize: function(options) {
            var view = this;

            view.optConfig = options.config;

            // view.listenTo(view, 'check:gmlist', view.updateSiblings);
        },

        render: function() {
            var view = this;

            view.$el.html(view.template(view.optConfig));
            return view;
        }

    });


    var App = Backbone.View.extend({

        el: 'body',

        qrTemplate: _.template($('#tmpl-side-qrcode').html()),

        events: function() {
            if (isMobile) {
                return {
                    'touchstart .js-buy-it': 'buyAction',
                    'click .js-gocart-it': 'cartAction',
                    'click .zx-access':'zxaccess',
                    'touchstart .js-qrcode-buy': 'qrcodeBuyTip',
                    'touchstart .js-hide-qrcode': 'hideQrcode',
                    'click .restore': 'restore',
                    'touchstart .js-confirm-it': 'submitOrder',
                    'click .js-cart-it': 'addCart'
                    	
                    	
                    	
                };
            } else {
                return {
                    'click .js-buy-it': 'buyAction',
                    'click .js-qrcode-buy': 'qrcodeBuyTip',
                    'click .js-hide-qrcode': 'hideQrcode',
                    'click .restore': 'restore',
                    'click .js-confirm-it': 'submitOrder'
                };
            }
        },

        setOption: function(options) {
            var view = this;

            _(view.config).extend(options);

            var sku = view.sku = window._global.sku;
            view.skuTree = sku.tree;  // 型号参数表
            view.skuMap = sku.map;    // 组合型号映射表：由型号表组合而成
            view.skuList = sku.list;  // 每种型号数据

            // 需要初始化的留言字段
            view.messages = sku.messages;

            // 如：颜色 和 尺码
            var keys = view.keys = _.pluck(view.skuTree, 'k');
            view.keysMsg = keys.join(' 和 ');

            view.values = _.pluck(view.skuTree, 'v');

            view.len = view.skuTree.length;

            // 只有一个 sku 的时候自动选择该 sku
            if (sku.single_sku) {
                var ids = [];
                _.each(view.values, function(value, key, list) {
                    var id = value[0].id;
                    ids.push(id);
                });
                var last = _({}).extend(view.skuMap);
                for (var i = 0, len = ids.length; i < len; i++) {
                    last = last[ids[i]];
                }
                view.selectedSku = view.skuList[last];
            }

            view.goodsId = window._global.goods_id;
            view.quota = window._global.quota || Infinity;
            view.buyQuantity = 1;

            // 商品总库存
            view.totalStock = sku.stock_num;

            // 显示的商品价格，可能为价格区间的字符串
            view.price = sku.price;

            // 二维码图片缓存
            view.qrCache = {};

            // 参与直接扫码活动别名
            view.activityAlias = window._global.activity_alias;
        },

        initialize: function(options) {
            var view = this;

            view.config = {};
            view.setOption(options);

            view.init();
        },

        init: function() {
            var view = this;

            view.showWxOptionMenu();

            view.hideTopBar();

            view.findEles();

            view.initCountdown();

            view.initStash();

            view.autoInit();

            view.adminPreview();

        },

        showWxOptionMenu: function() {
            var view = this;

            if (isWx) {
                wxReady(function() {
                    WeixinJSBridge.call('showOptionMenu');
                });
            }
        },

        initCountdown: function() {
            var view = this;

            if ($('.js-mini-counter').length) {
                $('.js-mini-counter').MiniCounter({
                    callback: function(left) {
                        $('.js-info-wrapper').hide();
                        view.buyBtn.prop('disabled', false).html('&nbsp;&nbsp;立即购买&nbsp;&nbsp;');
                        view.confirmBtn.prop('disabled', false).html('&nbsp;&nbsp;提交订单&nbsp;&nbsp;');
                    }
                });
            }
        },

        adminPreview: function() {
            var view = this;

            view.rootEle.on('switch_style', function(event, device) {
                view.switchStyle(device);
            });
        },

        autoInit: function() {
            var view = this;

            var hash = window.location.hash;
            var autoFlag = hash.indexOf('autoinit=1') !== -1;
            if (isMobile) {
                if (autoFlag) {
                    view.openSkuMobile();
                }
            } else {
                view.openSkuWeb();
            }
        },

        // 通过滚动页面实现隐藏topbar
        hideTopBar: function() {
            var topBar = $('.top-bar');
            var height = topBar.height();
            // alert(height);
            // window.addEventListener('load', function() {
            setTimeout(function() {
                window.scrollTo(0, height);
            }, 10);
            // });
        },

        initStash: function() {
            var view = this;

            var stash = window.stash = new Stash([], {
                maxSize: view.len
            });
            view.listenTo(stash, 'full:stash', view.updateGoodInfo);
            view.listenTo(stash, 'not_full:stash', view.updateGoodInfo);
        },

        initAdvOpts: function() {
            var view = this;

            view.advOptsView = new AdvOptsView({
                el: view.advOptsInner,
                config: {
                    keys: view.keys,
                    stock_num: view.totalStock,
                    quota: view.quota,
                    messages: view.messages,
                    is_mobile: isMobile
                }
            });

            view.advOpts.html(view.advOptsView.render().el);

            console.log(view.advOpts.html());
            
            view.confirmBtn = view.$('.js-confirm-it');
            view.infoWrapper = view.$('.info-wrapper').show();
            view.stockEle = view.$('.js-stock-num');
            view.bottomPriceEle = $('.js-bottom-price').hide();
            view.priceEle = view.$('.js-goods-price');
            view.quantityEle = view.$('.js-quantity');
            view.formEle = view.$('.js-form');

            view.modelsContainer = view.$('.js-goods-models');
            view.qrcodeBtn = view.$('.js-qrcode-buy');
            view.hideBtn = view.$('.js-hide-qrcode');
            view.buyGuide = view.$('.js-buy-guide');

            view.openFlag = false;
        },

        resetAdvOpts: function() {
            var view = this;

            view.openFlag = false;

            if (view.advOptsView) {
                view.advOptsView.remove();
                // view.advOptsView.empty()
                view.advOpts.html(view.modelsHtml);
                
                console.log(view.advOpts.html());
            }
        },

        initGmList: function() {
            var view = this;

            view.modelList = view.$('.model-list');
            var gmListViewArray = window.gmListViewArray = [];
            var allGms = window.allGms = new GmList([]);

            // idx => cid
            console.log(view.len);
            for (var i = 0; i < view.len; i++) {
                gmListViewArray[i] = new GmListView({
                    parentView: view.advOptsView,
                    el: view.modelList.eq(i),
                    collection: view.values[i],
                    idx: i
                });
            }

            // 只有一个型号时默认选中
            for (var j = 0; j < view.len; j++) {
                // if (view.values[j].length === 1) {
                gmListViewArray[j].$el.children(':not(.unavailable)').first().trigger(tapName);
                // }
            }

            console.log(allGms.models);
        },

        // 初始化购买数量
        initQuantity: function() {
            var view = this;

            var quantityView = window.quantityView = view.quantityView = new QuantityView({
                el: view.quantityEle,
                max: view.quota
            });
            view.listenTo(quantityView, 'set_quantity', view.updateBuyQuantity);
        },

        initPcBuy: function() {
            var view = this;

            view.initQrcodeBuy();
        },

        // 更新购买数量
        updateBuyQuantity: function(num) {
            var view = this;

            view.buyQuantity = num;
        },

        findEles: function() {
            var view = this;

            view.rootEle = $(document.documentElement);
            view.fullPage = view.$('.wap-page-goods');
            view.imageSwiper = view.$('.js-image-swiper');
            view.taoInfo = view.$('.custom-go-tao');
            view.returnBtn = view.$('.js-butn-return');
            view.buyBtn = view.$('.js-buy-it');
            view.confirmBtn = view.$('.js-confirm-it');
            view.componentsContainer = view.$('.js-components-container');
            view.advOpts = view.$('.adv-opts');
            view.advOptsInner = view.$('.adv-opts-inner');
            view.modelsHtml = view.advOptsInner[0].outerHTML;
            view.bottomOpts = view.$('.js-bottom-opts');
            view.qrcodeContainer = $('.js-qrcode-container');
        },

        closeAdvOpts: function(event) {
            event.preventDefault();

        },

        showFooter: function() {
            var view = this;

            view.fullPage.removeClass('show-footer');
        },

        showThumb: function() {
            var view = this;

            view.taoInfo.addClass('restore');
        },

        switchStyle: function(device) {
            var view = this;

            view.resetAdvOpts();
            switch (device) {
                case 'iphone':
                case 'samsung-note':
                    break;
                case 'pc':
                    motify.clear();
                    view.openSkuWeb();
                    break;
                default:
                    break;
            }
        },

        buyAction: function(event) {
            var view = this;

            console.log('buyAction');
            
            if (event) {
                event.preventDefault();
            }

            motify.clear();

            // 包含未上架、已售罄等不可购买的情况
            if (view.buyBtn.prop('disabled')) {
                return false;
            }

            // 网店未认证，无法进行交易
            if (!_global.team_certificate) {
                motify.log('该网店未通过认证，<br />暂时不支持购买。', 0);
                return false;
            }

            if (isAdmin && !isMobile) {
                motify.log('预览不支持进行购买，<br />实际效果请在手机上进行。', 0);
                return false;
            }

            //illegal
            if (!permissions.aliPay && !supportOutBuy) {
                if (!permissions.wxPay || (permissions.wxPay && !isWx)) {
                    motify.log('该商品无法购买，请联系商家。', 30000);
                    view.buyBtn.prop('disabled', true);
                    view.confirmBtn.prop('disabled', true);
                    return false;
                }
            }

            //outbuy
            if (!permissions.wxPay && !permissions.aliPay) {
                window.location.href = outBuyUrl;
            }

            //wxpay
            //alipay
            //...
            if (permissions.wxPay || permissions.aliPay) {

                if (view._deferred && typeof view._deferred.isResolved === 'function') {
                    if (!view._deferred.isResolved()) {
                        motify.log('亲，请稍等。');
                        return false;
                    }
                }
                view._deferred = $.Deferred().done(function() {
                	view.openSkuMobile();
                });
                if (event) {
                    $.kdt.log($.kdt.addParameter(_global.logURL, {
                        spm: $.kdt.spm(),
                        fm: 'click',
                        referer_url: encodeURIComponent(document.referrer),
                        title: '立即购买'
                    }), view._deferred);
                } else {
                    view._deferred.resolve();
                }
            }
        },

        
        cartAction: function(event) {
        	
        	  if (window._global.need_ajax_login) {
                  $.kdt.login(function() {
               	   		window._global.redirect_url=null;
                           window._global.need_ajax_login = false;
                      	 var baseUrl = window._global.baseurl;
                    	 window.location.href=baseUrl+'/index.php?r=buyer/gocart';
                       });
                  
                   } else {
                		 var baseUrl = window._global.baseurl;
                    	 window.location.href=baseUrl+'/index.php?r=buyer/gocart';
                   }
        	
        
        	
        	
        },
        
        zxaccess:function(event){
        	this.zx();
        	/*//判断是否
        	  if (window._global.need_ajax_login) {
                  $.kdt.login(function() {
               	   		window._global.redirect_url=null;
                           window._global.need_ajax_login = false;
                      	//登陆后
                       });
                  
                   } else {
                		 var baseUrl = window._global.baseurl;
                    	this.zx();
                   }
        	*/
        	
        },
        zx:function(){
        	
        	 motify.log('提交成功。');
        },
         
        qrcodeBuyTip: function(event) {
            var view = this;

            event.preventDefault();
            if (!view.qrcodeContainer.hasClass('shake')) {
                view.qrcodeContainer.addClass('active animated shake');
                setTimeout(function() {
                    view.qrcodeContainer.removeClass('animated shake');
                }, 1200);
            }

        },

        initQrcodeBuy: function() {
            var view = this;

            // 检查该二维码是否已经有缓存
            var skuId = view.selectedSku ? view.selectedSku.id : 0;
            var qrData = view.qrCache[skuId];
            if (qrData) {
                view.showQrcode(qrData);
            } else {
               /* view.geneQrcode(view.goodsId, skuId);*/
            }
        },

        openSkuMobile: function() {
            var view = this;

            if (!view.openFlag) {

                view.showFooter();
                view.showThumb();
                view.initAdvOpts();
                view.initQuantity();
                view.initGmList();
                view.hideOthers();

                // 页面滚动到商品标题
                view.scrollToTitle();

                view.openFlag = true;
            }
        },

        openSkuWeb: function() {
            var view = this;

            if (!view.openFlag) {

                view.initPcBuy();
                // view.initGmList();

                view.openFlag = true;
            }
        },

        restore: function() {
            var view = this;

            window.location.hash = '';
            window.location.reload();
        },

        // 隐藏底部固定条
        hideOthers: function() {
            var view = this;

            view.bottomOpts.hide();
            view.imageSwiper.hide();
            view.componentsContainer.hide();
        },

        // 获取购买相关的信息：留言、购买数量
        getFormData: function() {
            var view = this;

            var formData = {};

            // 如果包含留言字段
            if (view.messages.length > 0) {

                var arr = view.formEle.serializeArray();
                _(arr).each(function(element, index, list) {
                    formData[element.name] = $.trim(element.value);
                });

            }
            console.log(formData);
            return formData;
        },

        // 滚动到商品标题
        scrollToTitle: function() {
            var view = this;

            var top = $('.custom-go-tao').offset().top;
            setTimeout(function() {
                window.scrollTo(0, top);
            }, 10);
        },

        // 校验订单参数
        validOrder: function(postData) {
            var view = this;
            
            console.log('validOrder');

            var messages = view.messages;
            var validErrors = view.validErrors = [];
            for (var j = 0, len = messages.length; j < len; j++) {
                var message = messages[j];
                var key = 'message_' + j;
                var value = postData[key];

                if (_.isEmpty(value)) {

                    // 必填字段的校验
                    if (message.required == '1') {
                        validErrors.push({
                            key: 'required'
                        });
                        view.formEle.find('#ipt-' + j).focus();
                        motify.log('请填写你的' + message.name + '。');
                        return false;
                    }

                } else {

                    if (message.type == 'tel' && !Utils.validNumber(value)) {
                        validErrors.push({
                            key: 'number'
                        });
                        view.formEle.find('#ipt-' + j).focus();
                        motify.log('请填写正确的' + message.name + '。');
                        return false;
                    }
                    if (message.type == 'email' && !Utils.validEmail(value)) {
                        validErrors.push({
                            key: 'email'
                        });
                        view.formEle.find('#ipt-' + j).focus();
                        motify.log('请填写正确的' + message.name + '。');
                        return false;
                    }

                }
            }
            if (validErrors.length === 0) {
                return true;
            } else {
                return false;
            }

        },
        addCart:function(){
        	  var view = this;
        	  if (event) {
                  event.preventDefault();
              }

              // 包含未上架、已售罄等不可购买的情况
              if (view.confirmBtn.prop('disabled')) {
                  return false;
              }

              if (isAdmin && !isMobile) {
                  motify.log('预览不支持进行购买，<br />实际效果请在手机上进行。', 0);
                  return false;
              }
        	
              
        
                  if (!view.ajaxing) {

                      // sku
                      if (!view.selectedSku) {
                          motify.log('请选择 ' + view.keysMsg + '。');
                          view.scrollToTitle();
                          return false;
                      }

                      var postData = {
                          goods_id: view.goodsId,
                          sku_id: view.selectedSku.id,
                          price: view.selectedSku.price,
                          num: view.buyQuantity,
                          activity_alias: view.activityAlias
                      };

                      // 获取留言相关的表单数据
                      var formData = view.getFormData();

                      // 合并需要提交的数据
                      _(postData).extend(formData);

                      // 校验通过后才提交订单数据到服务器
                      if (view.validOrder(postData)) {
                    	  
                    	  
                          view.sendToServer_cart(postData);

                         
                      }
                  }
                 
        	
        },
        // 预提交订单
        submitOrder: function(event) {
            var view = this;

            console.log('submitOrder');
            
            if (event) {
                event.preventDefault();
            }

            // 包含未上架、已售罄等不可购买的情况
            if (view.confirmBtn.prop('disabled')) {
                return false;
            }

            if (isAdmin && !isMobile) {
                motify.log('预览不支持进行购买，<br />实际效果请在手机上进行。', 0);
                return false;
            }

            if (view._submitOrderDeferred && typeof view._submitOrderDeferred.isResolved === 'function') {
                if (!view._submitOrderDeferred.isResolved()) {
                    motify.log('提交订单中，请勿重复提交。');
                    return false;
                }
            }

            view._submitOrderDeferred = $.Deferred().done(function() {
                if (!view.ajaxing) {

                    // sku
                    if (!view.selectedSku) {
                        motify.log('请选择 ' + view.keysMsg + '。');
                        view.scrollToTitle();
                        return false;
                    }

                    var postData = {
                        goods_id: view.goodsId,
                        sku_id: view.selectedSku.id,
                        price: view.selectedSku.price,
                        num: view.buyQuantity,
                        activity_alias: view.activityAlias
                    };

                    // 获取留言相关的表单数据
                    var formData = view.getFormData();

                    // 合并需要提交的数据
                    _(postData).extend(formData);

                    // 校验通过后才提交订单数据到服务器
                    if (view.validOrder(postData)) {
                        view.sendToServer(postData);
                    }

                } else {

                    motify.log('提交订单中，请勿重复提交。');

                }
            });
            if (event) {
                $.kdt.log($.kdt.addParameter(_global.logURL, {
                    spm: $.kdt.spm(),
                    fm: 'click',
                    referer_url: encodeURIComponent(document.referrer),
                    title: '提交订单'
                }), view._submitOrderDeferred);
            } else {
                view._submitOrderDeferred.resolve();
            }
        },
        
  sendToServer_cart: function(postData) {
        	
            var view = this;

            if (window._global.need_ajax_login) {
           $.kdt.login(function() {
        	   		window._global.redirect_url=null;
                    window._global.need_ajax_login = false;
                    view._sendToServer_cart(postData);
                });
           
            } else {
                view._sendToServer_cart(postData);
            }
        },
        

        sendToServer: function(postData) {
        	
            var view = this;

            if (window._global.need_ajax_login) {
           $.kdt.login(function() {
        	   		window._global.redirect_url=null;
                    window._global.need_ajax_login = false;
                    view._sendToServer(postData);
                });
           
            } else {
                view._sendToServer(postData);
            }
        },

        // 提交订单数据到服务器
        _sendToServer: function(postData) {
            var view = this;
        
            var baseUrl = window._global.baseurl;
          //  alert(JSON.stringify(postData));
            $.ajax({
                url:baseUrl+'/index.php?r=buyer/SaveOrder',
                type: 'post',
                dataType: 'json',
                cache: false,
                timeout: 15000,
                data: postData,
                success: function(resp) {
                	   view.submitSuccess(resp, postData);//订单提交成功后 跳转到选择收货地址付款页面
                },
                error: function(xhr, errorType, error) {
                        
                    view.submitError(xhr, errorType, error);
                },
                complete: function() {
                    console.log('complete');
                    view.ajaxing = false;
                }
            });
        },
        
        
        // 提交购物车数据到服务器
        _sendToServer_cart: function(postData) {
            var view = this;
        
            var baseUrl = window._global.baseurl;
         
            $.ajax({
                url:baseUrl+'/index.php?r=buyer/SaveCart',
                type: 'post',
                dataType: 'json',
                cache: false,
                timeout: 15000,
                data: postData,
                beforeSend: function() {
                	
                    view.ajaxing = true;
                    
                },
                success: function(resp) {
                	
                	   motify.log(resp.msg);

             
                },
                error: function(xhr, errorType, error) {
                 motify.log('非常抱歉,服务器出错了');   
                	
                },
                complete: function() {
                    console.log('complete');
                    view.ajaxing = false;
                }
            });
        },
        

        submitSuccess: function(resp, postData) {
            var view = this;
           
            console.log('success', resp);
            var code = resp.code;
            if (code === 0) {
                // 成功

                view.buyBtn.html('&nbsp;&nbsp;立即购买&nbsp;&nbsp;');
                view.confirmBtn.html('&nbsp;&nbsp;确认提交&nbsp;&nbsp;');

                var orderID = resp.data.order_id;
             
                if (!orderID|| !resp.data.trade_confirm_url) {
                    motify.log('订单生成失败，请联系管理员。');
                    return false;
                }

                window.location.href = resp.data.trade_confirm_url;

            } else if (code === 11010) {
                // 价格发生变动

                Utils.needConfirm(resp.msg, function() {
                    // motify.log('正在处理中...');
                    var newPostData = {
                        accept_price: 1
                    };
                    _(newPostData).extend(postData);
                    view.sendToServer(newPostData);
                }, function() {
                    // 取消下单，刷新商品详情页
                    window.location.reload();
                });

            } else if (code === 11011) {
                // {11011: 商品已售罄}

                motify.log(resp.msg);
                view.buyBtn.html('该商品已售罄');
                view.confirmBtn.html('该商品已售罄');
                view.buyBtn.prop('disabled', true);
                view.confirmBtn.prop('disabled', true);

            } else if (code === 11012) {
                // 打开商品页面时未下架，下单过程中商品被下架了

                motify.log(resp.msg);
                view.buyBtn.html('该商品已经下架');
                view.confirmBtn.html('该商品已经下架');
                view.buyBtn.prop('disabled', true);
                view.confirmBtn.prop('disabled', true);

            } else if (code === 11013) {
                // {11013: 此商品不存在}

                motify.log(resp.msg);

                view.confirmBtn.html('&nbsp;&nbsp;提交订单&nbsp;&nbsp;');
                view.buyBtn.html('&nbsp;&nbsp;立即购买&nbsp;&nbsp;');
                // window.location.href = '';

            } else if (code === 11020) {
                // {11020: sku不存在}

                alert(resp.msg);
                motify.log('正在刷新页面...');
                window.location.reload();

            } else if (code === 11111) {
                alert(resp.msg);
                motify.log('正在刷新页面...');
                window.location.reload();

            }else {
                // 其他情况
                // {11015: 该商品每人限购N件}
            	
                motify.log(resp.msg);
                alert(resp.msg);
            window.location.reload();
                //view.confirmBtn.html('&nbsp;&nbsp;提交订单&nbsp;&nbsp;');
                //view.buyBtn.html('&nbsp;&nbsp;立即购买&nbsp;&nbsp;');

            }
        },

        submitError: function(xhr, errorType, error) {
            var view = this;

            if (isAdmin) {
                alert(JSON.stringify(xhr));
            }
            motify.log('购买失败，请重试。');
            view.confirmBtn.html('&nbsp;&nbsp;提交订单&nbsp;&nbsp;');
            view.buyBtn.html('&nbsp;&nbsp;立即购买&nbsp;&nbsp;');
        },

        // 更新页面上的库存
        updateStock: function(num) {
            var view = this;

            view.stockEle.html(num);
            if (window.quantityView) {
                window.quantityView.trigger('update_max', num);
            }
        },

        // 更新页面上的价格
        updatePrice: function(num) {
            var view = this;

            view.priceEle.html(num);
        },

        // 更新页面上商品的信息
        updateGoodInfo: function(sku, models) {
            var view = this;

            console.log('sku: ', sku);

            if (sku) {

                // var ids = _(models).pluck('id');
                // console.log(ids);

                var skuInfo = view.selectedSku = window._global.sku.list[sku];

                view.updateStock(skuInfo.stock_num);
                view.updatePrice(Number(skuInfo.price).toFixed(2));

            } else {

                view.selectedSku = sku;
                view.updateStock(view.totalStock);
                view.updatePrice(view.price);

            }
        },

        // 生成关注二维码
/*        geneQrcode: function(goodsId, skuId) {
            var view = this;

            var postData = {
                kdt_id: window._global.kdt_id,
                goods_id: goodsId,
                alias: window._global.alias,
                type: 'goods'
            };

            var baseUrl = window._global.url.wap;
            $.ajax({
                url: baseUrl + '/common/url/goods.jsonp',
                type: 'GET',
                dataType: 'jsonp',
                cache: false,
                data: postData,
                beforeSend: function() {
                    view.ajaxing = true;
                    // view.qrcodeBtn.html('&nbsp;&nbsp;提交中...');
                },
                success: function(resp) {
                    var code = resp.code;
                    if (code === 0) {
                        view.showQrcode(resp.data);
                        view.cacheQrcode({
                            sku_id: skuId,
                            data: resp.data
                        });
                    } else {
                        motify.log(resp.msg);
                    }
                },
                error: function() {
                    console.log('error');
                    motify.log('二维码生成失败，请重试～～');
                },
                complete: function() {
                    console.log('complete');
                    view.ajaxing = false;
                    // view.qrcodeBtn.html('&nbsp;&nbsp;立即购买&nbsp;&nbsp;');
                }
            });

        },*/

        cacheQrcode: function(qrData) {
            var view = this;

            view.qrCache[qrData.sku_id] = qrData.data;
        },

        showQrcode: function(qrData) {
            var view = this;

            view.qrcodeContainer.html(view.qrTemplate(qrData));
        },

        hideQrcode: function(event) {
            var view = this;

            view.buyGuide.hide();
            view.modelsContainer.show();
            view.qrcodeBtn.show();
            view.hideBtn.hide();
        }

    });

    // ----------------------- Init App ---------------------- //
    var motify = window.motify;
    window.app = new App();

});
